// app/controller/upload.js
const Controller = require('egg').Controller;
const path = require('path');
const fs = require('fs');
class UploadController extends Controller {

  async upload() {
    const ctx = this.ctx;
    // 检查是否有文件上传
    if (ctx.request.files && ctx.request.files.length > 0) {
      const file = ctx.request.files[0]; // 获取第一个文件对象
      console.log('file', file)

      // 移动文件到指定目录
      const sourcePath = path.join(ctx.app.baseDir, file.filepath);

      // 生成最终文件名（包含时间戳）
      const finalName = `${Date.now()}_${file.filename}`;
      const targetPath = path.join(ctx.app.baseDir, 'app/public/uploads', finalName);
      await copyfile(sourcePath, targetPath);

      ctx.body = {
        code: 20000,
        url: `${ctx.request.protocol}://${ctx.request.host}/public/uploads/${finalName}`
      }; // 返回文件访问路径
    } else {
      ctx.throw(400, 'No files were uploaded.');
    }
  }



}

function copyfile(source, target) {
  console.log('复制文件 从source   ' + source + '     到target   ' + target + ':')
  return new Promise((resolve, reject) => {
    const readStream = fs.createReadStream(source);
    const writeStream = fs.createWriteStream(target);

    readStream.on('error', reject);
    writeStream.on('error', reject);
    writeStream.on('finish', resolve);

    readStream.pipe(writeStream);
  });
}

module.exports = UploadController;